<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\models\User;
use app\models\Category;
use app\models\Article;

class ArticleController extends BaseController
{
  //资讯分类列表
  public function actionCateList(){
    $cate_list = Category::find()->where(['type' => 1, 'status' => 1])->andWhere("id <> 6")->select('id, name')->all();
    return Re::data(['data' => $cate_list]);
  }

  //资讯列表
  public function actionArticleList(){
    $page = Yii::$app->request->post('page', 0);
    $cate_id = Yii::$app->request->post('cate_id', 0);
    $title = Yii::$app->request->post('title', '');
    $article_query = Article::find()->where(['status' => 1])->andWhere('cate_id <> 6');
    if ($cate_id) {
      $article_query->andWhere(['cate_id' => $cate_id]);
    }
    if ($title) {
      $article_query->andWhere(['like', 'title', $title]);
    }
    $article_list = $article_query->orderBy("created_at desc")->limit(10)->offset(10*$page)->all();
    $article_data = [];
    if ($article_list) {
      foreach ($article_list as $v) {
        $article_data[] = [
          'id' => $v->id,
          'title' => $v->title,
          'cover' => $v->cover,
          'source' => $v->source,
          'created_time' => date("Y-m-d", $v->created_at),
        ];
      }
    }
    return Re::data(['data' => $article_data]);
  }

  //资讯详情
  public function actionArticleDetail(){
    $id = Yii::$app->request->post('id', 0);
    $article = Article::findOne($id);
    if (!$article) {
      return Re::data(null, '资讯信息读取失败', Re::ERROR);
    }
    $data = [
      'id' => $article->id,
      'title' => $article->title,
      'cover' => $article->cover,
      'content' => $article->content,
      //'content' => '',
      'source' => $article->source,
      'created_time' => date("Y-m-d", $article->created_at),
    ];
    return Re::data(['data' => $data]);
  }
}
